class MusicPlayer{
	constructor({store, src, loop, volume} = {}) {
		this.canPlay = false;
		this.store = store;
		this.playTicker = null;
		this.loop = loop;// 安卓平台从获取ctx['loop']为undefined，索性将该属性作为成员变量
		
		let ctx = this.ctx = uni.createInnerAudioContext();
		ctx.autoplay = false;
		ctx.loop = loop;
		ctx.src = src;
		ctx.volume = volume;
		
		ctx.onCanplay(() => {
			if(this.canPlay) return;
			this.canPlay = true;
			this.togglePlay();
		})
	}
	addListener(event, callback) {
		this.ctx[event].call(this.ctx, () => {
			if(event == 'onCanplay'){
				this.canPlay = true;
				// uni.showToast({
				// 	title: 'onCanplay',
				// 	icon: 'none'
				// })
			}
			callback();
		});
	}
	callMethod(method, arg) {
		if(method == 'play' && !this.get('paused')) return false;// 如果要调用播放方法而其实已经正在播放了，则不重复执行
		this.ctx[method].call(this.ctx, arg);
	}
	get(key) {
		return this.ctx[key];
	}
	togglePlay() {
		this.store.commit('setPlaying', !this.store.state.playing);
		this.playTicker && clearInterval(this.playTicker);
		if(this.store.state.playing){
			this.startPlayTicker();
		}
		else{
			this.callMethod('pause');
		}
	}
	startPlayTicker() {
		this.callMethod('play');
		this.playTicker && clearInterval(this.playTicker);
		if(this.store.state.music.progress >= 100){
			this.callMethod('seek', 0);
			this.store.commit('setPlayProgress', 0);
		}
		this.playTicker = setInterval(() => {
			let progress = this.store.state.music.progress + (100/this.store.state.music.length);// 100 除以歌曲长度（单位秒）为每秒钟进度条要增加的进度					
			this.store.commit('setPlayProgress', progress);
			if(progress >= 100){
				clearInterval(this.playTicker);
				if(this.loop){// 循环播放时播放完成后重新播放
					this.store.commit('setPlayProgress', 0);
					this.callMethod('seek', 0);
					this.startPlayTicker();
				}
				else{
					this.togglePlay();
				}
			}
		}, 1000);
	}
	changingProgress(progress) {// 拖动进度条的过程中调用
		this.playTicker && clearInterval(this.playTicker);// 拖动进度条过程中暂时停止定时器，以防抖动
		this.store.commit('setPlayProgress', progress);
	}
	changedProgress(progress) {// 拖动进度条完成后调用
		this.store.commit('setPlayProgress', progress);
		this.callMethod('seek', this.store.getters.playTime);
		this.store.state.playing && this.startPlayTicker();
	}
	changeVolume(volume) {
		this.ctx.volume = volume;
		this.store.commit('setVolume', volume);
	}
}

export {
	MusicPlayer
}